package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增收货地址
     */
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        // 设置默认地址为false
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 展示当前用户的地址列表
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        return addressBookMapper.selectAllByUserId(addressBook);

    }

    /**
     * 查询当前用户的默认地址
     *
     * @return
     */
    @Override
    public AddressBook queryByDefault() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        List<AddressBook> addressBookList = addressBookMapper.selectAllByUserId(addressBook);
        if (addressBookList != null && addressBookList.size() == 1) {
            return addressBookList.get(0);
        }

        return null;
    }

    /**
     * 设置默认地址
     *
     * @param id
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        // 先对userid下所有地址isDefault都改成0
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.setIsDefaultIsFalse(userId);
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook queryById(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList = addressBookMapper.selectAllByUserId(addressBook);
        return addressBookList.get(0);
    }

    /**
     * 根据Id修改地址
     *
     * @param addressBook
     */
    @Override
    public void updateById(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void delById(Long id){
        addressBookMapper.delete(id);
    }

}
